package letcode.problem.dynamicProgra;

/**
 * https://leetcode.cn/problems/unique-paths-ii/description/?envType=study-plan-v2&envId=dynamic-programming
 * */
public class UniquePathII {
    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {

        int x = obstacleGrid.length;
        int y = obstacleGrid[0].length;
        if (obstacleGrid[x - 1][y - 1] != 0) {
            return 0;
        }
        int[][] dp = new int[x][y];
        for (int i = 0; i < y; i++) {
            dp[0][i] = 1;
            if (obstacleGrid[0][i] != 0) {
                dp[0][i] = 0;
            }
        }
        for (int i = 0; i < x; i++) {
            dp[i][0] = 1;
            if (obstacleGrid[i][0] != 0) {
                dp[i][0] = 0;
            }
        }
        for (int i = 1; i < x; i++) {
            for (int j = 1; j < y; j++) {
                int left = 0;
                if (obstacleGrid[i - 1][j] == 0) {
                    left = dp[i - 1][j];
                }
                int right = 0;
                if (obstacleGrid[i][j - 1] == 0) {
                    right = dp[i][j - 1];
                }
                dp[i][j] = left + right;
            }
        }
        return dp[x - 1][y - 1];
    }
}
